package com.demo.config;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author wangfengchen
 */
@Component
public class I18nHelper {

  @Autowired
  private MessageSource messageSource;
  @Autowired
  private HttpServletRequest request;


  /**
   * 根据消息键和参数 获取消息 委托给spring messageSource
   *
   * @param code 消息键
   * @param args 参数
   * @return 获取国际化翻译值
   */
  public String getMessage(HttpServletRequest request, int code, Object... args) {
    LocaleResolver localeResolver = SpringUtil.getBean(LocaleResolver.class);
    return messageSource.getMessage(Integer.toString(code), args, "", localeResolver.resolveLocale(request));
  }

  public String getMessage(HttpServletRequest request, String key, Object... args) {
    LocaleResolver localeResolver = SpringUtil.getBean(LocaleResolver.class);
    return messageSource.getMessage(key, args, "", localeResolver.resolveLocale(request));
  }

  public String getMessage(int code, Object... args) {
    return messageSource.getMessage(Integer.toString(code), args, "", resolveLocale());
  }

  public String getMessage(String key, Object... args) {
    return messageSource.getMessage(key, args, "", resolveLocale());
  }

  private Locale resolveLocale() {
    if (request == null) {
      return Locale.SIMPLIFIED_CHINESE;
    }
    LocaleResolver localeResolver = SpringUtil.getBean(LocaleResolver.class);
    return localeResolver.resolveLocale(request);
  }

}
